package com.jshongli.myapplication.inspect;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.model.LatLng;
import com.google.gson.Gson;
import com.jshongli.myapplication.R;
import com.jshongli.myapplication.base.BaseActivity;
import com.jshongli.myapplication.common.callback.MyCallback;
import com.jshongli.myapplication.common.callback.ResponseCallback;
import com.jshongli.myapplication.common.callback.UpdateCallback;
import com.jshongli.myapplication.common.utils.AccountManager;
import com.jshongli.myapplication.common.utils.CroodUtils;
import com.jshongli.myapplication.common.utils.MyDialog;
import com.jshongli.myapplication.common.utils.NotificationUtil;
import com.jshongli.myapplication.common.utils.StringUtils;
import com.jshongli.myapplication.common.utils.SuccessDialogUtils;
import com.jshongli.myapplication.common.utils.ToastUtils;
import com.jshongli.myapplication.common.utils.URLUtils;
import com.jshongli.myapplication.model.base.Update;
import com.jshongli.myapplication.model.inspect.PatrolBean;
import com.jshongli.myapplication.model.inspect.PointBean;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.MediaType;

public class ContinuePatrolActivity extends BaseActivity {

    public static ContinuePatrolActivity mActivity;

    @BindView(R.id.mapView)
    MapView mMapView;
    @BindView(R.id.tv_start)
    TextView tv_start;
    @BindView(R.id.tv_end)
    TextView tv_end;
    @BindView(R.id.tv_edit)
    ImageView tv_edit;
    @BindView(R.id.tv_sign)
    TextView tv_sign;
    @BindView(R.id.dingweiyuandian)
    ImageView dingweiyuandian;
    @BindView(R.id.autosign)
    CheckBox autosign;

    String pId;
    String Cable;
    String tracks;
    BaiduMap mBaiduMap;
    SuccessDialogUtils tipDialog;

    List<PointBean.DATA> point_List = new ArrayList<>();
    List<LatLng> LatLng_List = new ArrayList<>();

    //region 计时器——20秒刷新一次列表
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    update();
                    break;
            }
            super.handleMessage(msg);
        }

        void update() {
            // 刷新内容
            Clockin();
//            Log.e("测试定时","1");
        }
    };

    Timer timer = null;
    TimerTask task = null;

    private void initTimer() {
        stopTimer();
        timer = new Timer();
        task = new TimerTask() {
            public void run() {

                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);

            }
        };

        timer.schedule(task, 0, 1000 * 300);
    }

    /**
     * 结束计时器
     */
    private void stopTimer() {
        if (this.timer != null) {
            this.timer.cancel();
        }
    }

    //endregion

    @Override
    protected int getLayoutId() {
        return R.layout.activity_continue_patrol;
    }

    @Override
    protected void initView() {
        super.initView();

        mToolbar.setTitle("开始巡查");
        initToolbarBack2(mToolbar);
        initTvRightText(mToolbar,"签到记录",null);

        mBaiduMap = mMapView.getMap();

        autosign.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(compoundButton.isChecked()) {
                    ToastUtils.show(mContext, "已开启自动签到功能，每隔五分钟自动进行一次打卡");
                    initTimer();
                }else {
                    ToastUtils.show(mContext, "已关闭自动签到功能，请手动进行打卡");
                    stopTimer();
                }

            }
        });

        initPD();
        getPoint();

    }

    //region initPD
    private ProgressDialog pd;

    private void initPD() {
        pd = new ProgressDialog(mContext);
        pd.setCanceledOnTouchOutside(false);
        pd.setCancelable(false);
        pd.setMessage("正在加载中...");
    }
    //endregion

    private void getPoint()
    {
        Map<String, String> map = new HashMap<>();
        OkHttpUtils.get().url(URLUtils.URLNoToken("manageAPI/bizPoint/getList")).addHeader("Authorization", AccountManager.getToken()).params(map).tag(this)
                .build().execute(new MyCallback<PointBean>(mContext) {

            @Override
            public void onSuccess(PointBean response) {
                pd.dismiss();
                if(response.success)
                {
                    point_List.clear();
                    point_List.addAll(response.data);
                    LatLng_List.clear();
                    for(PointBean.DATA item : point_List)
                    {
                        String []lonlatarr = item.lonLat.split(",");
                        addMaker(item.pileNum,lonlatarr[1],lonlatarr[0]);
                        LatLng_List.add(new LatLng(Double.valueOf(lonlatarr[1]), Double.valueOf(lonlatarr[0])));
                    }


                }else {
                    ToastUtils.show(mContext, "数据解析出错");
                }
            }

            @Override
            public void onFail(PointBean response) {
                super.onFail(response);
                ToastUtils.show(mContext, "获取点位失败，请重新进入");
            }
        });

    }

    private void addMaker(String title, String latitude,String longitude) {
        //构建中心点
        LatLng point = new LatLng(Double.valueOf(latitude), Double.valueOf(longitude));
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions().position(point).icon(BitmapDescriptorFactory.fromResource(R.mipmap.dianwei)).draggable(true);
        TextOptions textOptions = new TextOptions()
                .bgColor(0xAAFFFF00)  //設置文字覆盖物背景颜色
                .fontSize(25)  //设置字体大小
                .fontColor(0xFFFF00FF)// 设置字体颜色
                .text(title)  //文字内容
                .rotate(0)  //设置文字的旋转角度
                .position(point)
                ;



        //构造CircleOptions对象
        CircleOptions mCircleOptions = new CircleOptions().center(point)
                .radius(500)
                .fillColor(Color.argb(100,93,232, 204)) //填充颜色
                .stroke(new Stroke(5, 0xAA00ff00)); //边框宽和边框颜色

        //在地图上显示圆
        mBaiduMap.addOverlay(mCircleOptions);
        //在地图上添加Marker，并显示
        mBaiduMap.addOverlay(option);
        mBaiduMap.addOverlay(textOptions );//地图上添加mark

    }

    //region 地图生命周期
    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        if(mLocationClient != null)
        {
            mLocationClient.stop();
        }
        mBaiduMap.setMyLocationEnabled(false);
        mMapView = null;
        mActivity = null;

        if (task != null) {
            task.cancel();
            task = null;
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }
    //endregion

    @Override
    protected void initData() {
        super.initData();

        mActivity = this;

        //创建巡查记录
        pId = getIntent().getStringExtra("pId");
        Cable = getIntent().getStringExtra("cable");
        tracks = getIntent().getStringExtra("tracks");

        if(tracks != null)
        {
            if(tracks.length()>10){
                String[] trackarr = tracks.substring(2,tracks.length()-2).split("],\\[");
                for(String gj : trackarr)
                {
                    String[] jwdarr = gj.split(",");

                    LatLng latLng = new LatLng(Double.parseDouble(jwdarr[1]), Double.parseDouble(jwdarr[0]));
                    oldpoints.add(latLng);
                }
            }
        }

//        add();
    }

    //region HTTP -- 新增巡检记录-post
    //{
    //    "success": true,
    //    "msg": "success",
    //    "code": 0,
    //    "timestamp": 1665295311739,
    //    "data": "131",
    //    "count": 1
    //}
    private void add() {
        String url = URLUtils.URLNoToken("manageAPI/bizPatrol/add");

        Map<String, String> map = new HashMap<String, String>();

        OkHttpUtils
                .post()
                .url(url)
                .params(map)
                .addHeader("Authorization", AccountManager.getToken())
                .tag(this)
                .build()
                .execute(new ResponseCallback<PatrolBean>(mContext) {

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        super.onError(call, e, id);
                        ToastUtils.show(mContext,"创建巡查失败，请重新进入");
                        finish();
                    }

                    @Override
                    public void onResponse(final PatrolBean response, int id) {

                        if (response.code == 0) {
                            pd.dismiss();
                            pId = String.valueOf(response.data.id);
                        } else {
                            ToastUtils.show(mContext,"创建巡查失败，请重新进入");
                            finish();
                        }
                    }
                });
    }
    //endregion

    @OnClick({R.id.tv_start, R.id.tv_end, R.id.tv_edit,R.id.tv_sign,R.id.dingweiyuandian})
    public void onClick(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.tv_start:
                pd.show();
                initMap();

                break;
            case R.id.tv_end:
                initDialogInfo();
                break;
            case R.id.tv_edit:
                bundle.putString("pId", pId);
                bundle.putString("Cable", Cable);
                bundle.putString("wd", lastPoints.latitude + "");
                bundle.putString("jd", lastPoints.longitude + "");
                openActivity(EventCreatActivity.class, bundle, false);
                break;
            case R.id.tv_sign:
                bundle.putString("pId", pId);
                bundle.putString("Cable", Cable);
                bundle.putString("wd", lastPoints.latitude + "");
                bundle.putString("jd", lastPoints.longitude + "");
                openActivity(SignCreateActivity.class, bundle, false);
                break;
            case R.id.dingweiyuandian:
                btn_restarlocation();
                break;
        }
    }

    //region 通过LocationClient发起定位
    public LocationClient mLocationClient = null;

    private void initMap() {

        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                MyLocationConfiguration.LocationMode.NORMAL, true, null));

        mBaiduMap.setOnMapTouchListener(new BaiduMap.OnMapTouchListener() {
            @Override
            public void onTouch(MotionEvent motionEvent) {
                switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
                    case MotionEvent.ACTION_MOVE:
                        dingweiyuandian.setImageResource(R.mipmap.weidingwei);

                        break;
                }

            }
        });


        mLocationClient = new LocationClient(this);

//通过LocationClientOption设置LocationClient相关参数
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
//        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);

//设置locationClientOption
        mLocationClient.setLocOption(option);

//注册LocationListener监听器
        MyLocationListener myLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myLocationListener);
//开启地图定位图层
        mLocationClient.start();
        NotificationUtil.setNotification(mContext, "正在使用定位...");


        initTimer();

    }
    //endregion

    //region 定位信息反馈
    LatLng lastPoints;
    private boolean isFirstLoc = true; // 是否首次定位
    List<LatLng> points = new ArrayList<LatLng>();
    List<LatLng> oldpoints = new ArrayList<LatLng>();
    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }

            Log.d("weidu --- ", location.getLatitude() + "");
            Log.d("jingdu --- ", location.getLongitude() + "");



            if (location.getLocType() == BDLocation.TypeServerError) {
                pd.dismiss();
                ToastUtils.show(mContext, "服务器错误，请检查");
                return;
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                pd.dismiss();
                ToastUtils.show(mContext, "网络错误，请检查");
                return;
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                pd.dismiss();
                ToastUtils.show(mContext, "手机模式错误，请检查是否飞行");
                return;
            }


            if (isFirstLoc) {//首次定位
                /**第一个点很重要，决定了轨迹的效果，gps刚接收到信号时返回的一些点精度不高，
                 * 尽量选一个精度相对较高的起始点，这个过程大概从gps刚接收到信号后5-10秒就可以完成，不影响效果。
                 * 注：gps接收卫星信号少则十几秒钟，多则几分钟，
                 * 如果长时间手机收不到gps，退出，重启手机再试，这是硬件的原因
                 */
                LatLng ll = null;

                //选一个精度相对较高的起始点
                ll = getMostAccuracyLocation(location);
                if (ll == null) {
                    return;
                }
                isFirstLoc = false;

                points.add(ll);//加入集合
                lastPoints = ll;
                addTrack();
                tv_start.setVisibility(View.GONE);
                tv_end.setVisibility(View.VISIBLE);
                tv_edit.setVisibility(View.VISIBLE);
                tv_sign.setVisibility(View.VISIBLE);
                dingweiyuandian.setVisibility(View.VISIBLE);
                autosign.setVisibility(View.VISIBLE);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.show(mContext, "已开启自动签到功能，每隔五分钟自动进行一次打卡");
                    }
                }, 3000);

                Clockin();
                //显示当前定位点，缩放地图
                locateAndZoom(location, ll);

                //标记起点图层位置
                MarkerOptions oStart = new MarkerOptions();// 地图标记覆盖物参数配置类
                oStart.position(points.get(0));// 覆盖物位置点，第一个点为起点
                BitmapDescriptor bitmap = BitmapDescriptorFactory
                        .fromResource(R.mipmap.map_start);
                oStart.icon(bitmap);// 设置覆盖物图片
                mBaiduMap.addOverlay(oStart); // 在地图上添加此图层


                //将points集合中的点绘制轨迹线条图层，显示在地图上
                OverlayOptions oldoPolyline = new PolylineOptions().width(13).color(0xAAFF0000).points(oldpoints);
                Polyline moldPolyline = (Polyline) mBaiduMap.addOverlay(oldoPolyline);

                //起始点图层也会被清除，重新绘画
                MarkerOptions oldStart = new MarkerOptions();
                oldStart.position(oldpoints.get(0));
                BitmapDescriptor bitmap1 = BitmapDescriptorFactory
                        .fromResource(R.mipmap.map_start);
                oldStart.icon(bitmap1);
                mBaiduMap.addOverlay(oldStart);

                //起始点图层也会被清除，重新绘画
                MarkerOptions oldend = new MarkerOptions();
                oldend.position(oldpoints.get(oldpoints.size()-1));
                BitmapDescriptor bitmap2 = BitmapDescriptorFactory
                        .fromResource(R.mipmap.map_end);
                oldend.icon(bitmap2);
                mBaiduMap.addOverlay(oldend);


                return;//画轨迹最少得2个点，首地定位到这里就可以返回了
            }

            //从第二个点开始
            LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());

            //sdk回调gps位置的频率是1秒1个，位置点太近动态画在图上不是很明显，可以设置点之间距离大于为5米才添加到集合中
            if (CroodUtils.getDistance(lastPoints, ll) < 30) {
                return;
            }

            points.add(ll);//如果要运动完成后画整个轨迹，位置点都在这个集合中

            lastPoints = ll;
            Log.e("dis---", (CroodUtils.getDistance(lastPoints, ll)) + "");
            addTrack();

            //显示当前定位点，缩放地图
            locateAndZoom(location, ll);

            //清除上一次轨迹，避免重叠绘画
            mMapView.getMap().clear();

            //起始点图层也会被清除，重新绘画
            MarkerOptions oStart = new MarkerOptions();
            oStart.position(points.get(0));
            BitmapDescriptor bitmap = BitmapDescriptorFactory
                    .fromResource(R.mipmap.map_start);
            oStart.icon(bitmap);
            mBaiduMap.addOverlay(oStart);

            //将points集合中的点绘制轨迹线条图层，显示在地图上
            OverlayOptions ooPolyline = new PolylineOptions().width(13).color(0xAAFF0000).points(points);
            Polyline mPolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline);

            //将points集合中的点绘制轨迹线条图层，显示在地图上
            OverlayOptions oldoPolyline = new PolylineOptions().width(13).color(0xAAFF0000).points(oldpoints);
            Polyline moldPolyline = (Polyline) mBaiduMap.addOverlay(oldoPolyline);

            //起始点图层也会被清除，重新绘画
            MarkerOptions oldStart = new MarkerOptions();
            oldStart.position(oldpoints.get(0));
            BitmapDescriptor bitmap1 = BitmapDescriptorFactory
                    .fromResource(R.mipmap.map_start);
            oldStart.icon(bitmap1);
            mBaiduMap.addOverlay(oldStart);

            //起始点图层也会被清除，重新绘画
            MarkerOptions oldend = new MarkerOptions();
            oldend.position(oldpoints.get(oldpoints.size()-1));
            BitmapDescriptor bitmap2 = BitmapDescriptorFactory
                    .fromResource(R.mipmap.map_end);
            oldend.icon(bitmap2);
            mBaiduMap.addOverlay(oldend);

        }
    }
    //endregion

    //region 中心位置
    private void locateAndZoom(BDLocation location, LatLng ll) {
        /**
         * 记录当前经纬度，当位置不变，手机转动，取得方向传感器的方向，
         给地图重新设置位置参数，在跟随模式下可使地图箭头随手机转动而转动
         */
//        mCurrentLat = location.getLatitude();
//        mCurrentLon = location.getLongitude();
        MyLocationData locData = new MyLocationData.Builder().accuracy(0)//去掉精度圈
                //此mCurrentDirection为自己获取到的手机传感器方向信息，顺时针0-360
                .direction(location.getDirection()).latitude(location.getLatitude())
                .longitude(location.getLongitude()).build();
        mBaiduMap.setMyLocationData(locData);//显示当前定位位置点

        //给地图设置缩放中心点，和缩放比例值
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(ll).zoom(18.0f);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
    }
    //endregion

    //region 获取精准定位
    private LatLng getMostAccuracyLocation(final BDLocation location) {

        if (location.getRadius() > 50) {//gps位置精度大于25米的点直接弃用
            return null;
        }

        LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());

        if (lastPoints == null) {
            lastPoints = ll;
            return null;
        }
//        if (CroodUtils.getDistance(lastPoints, ll) > 5) {
//            lastPoints = ll;
//            points.clear();//有两点位置大于5，重新来过
//            return null;
//        }
        points.add(ll);
        lastPoints = ll;
        //有5个连续的点之间的距离小于5，认为gps已稳定，以最新的点为起始点
        if (points.size() >= 5) {
            points.clear();
            Log.e("稳定点---------", "");
            pd.dismiss();
            return ll;
        }
        return null;
    }
    //endregion

    //region HTTP -- 巡查轨迹单条新增-post
    private void addTrack() {
        String url = URLUtils.URLNoToken("manageAPI/bizPatrol/edit");

//        List<String>jwdarr = new ArrayList<>();

        List<LatLng> newpoints = new ArrayList<LatLng>();
        newpoints.addAll(oldpoints);
        newpoints.addAll(points);


        String jwdstr = "";
        for (LatLng item : newpoints)
        {
            String jwd =  String.valueOf(item.longitude)+","+String.valueOf(item.latitude);
//            jwdarr.add("["+jwd+"]");
            jwdstr = jwdstr+"["+jwd+"],";
        }

        Map<String, String> map = new HashMap<String, String>();
        map.put("track", "["+jwdstr.substring(0,jwdstr.length()-1)+ "]");
        map.put("id", pId);
//        map.put("status", pId);
        Gson gson = new Gson();
        final String s = gson.toJson(map);

        OkHttpUtils
                .postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .addHeader("Authorization", AccountManager.getToken())
                .content(s)
                .tag(this)
                .build()
                .execute(new UpdateCallback<Update>(mContext) {

                    @Override
                    public void onSuccess(Update response) {
                        Log.d("上传轨迹","成功");
                    }

                    @Override
                    public void onUpdating() {

                    }

                    @Override
                    public void onUpdateFailed() {

                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        super.onError(call, e, id);
                        Log.d("上传轨迹","失败");
                    }
                });
    }
    //endregion

    //region Dialog -- 是否结束
    MyDialog infoDialog;
    private void initDialogInfo() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_tip, null);
        infoDialog = new MyDialog(mContext, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, view, R.style.loading_dialog, Gravity.CENTER);
        infoDialog.setCancelable(false);

//        TextView txt = view.findViewById(R.id.txt);
//        LinearLayout ll_info = view.findViewById(R.id.ll_info);
        TextView tv_pos = view.findViewById(R.id.tv_pos);
        TextView tv_neg = view.findViewById(R.id.tv_neg);
        TextView tv_tips = view.findViewById(R.id.tv_tips);

        tv_neg.setText("确认结束");
        tv_pos.setText("继续巡查");
        tv_tips.setText("是否结束巡查");


        tv_pos.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                infoDialog.dismiss();
            }
        });

        tv_neg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishPatrol();
                infoDialog.dismiss();
            }
        });


        infoDialog.show();
    }
    //endregion

    //region HTTP -- 完成巡检记录-post
    private void finishPatrol() {
        String url = URLUtils.URLNoToken("manageAPI/bizPatrol/edit");

        Map<String, String> map = new HashMap<String, String>();
        map.put("id", pId);
        map.put("status", "2");
        Gson gson = new Gson();
        final String s = gson.toJson(map);
        OkHttpUtils
                .postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .addHeader("Authorization", AccountManager.getToken())
                .content(s)
                .tag(this)
                .build()
                .execute(new UpdateCallback<Update>(mContext) {
                    @Override
                    public void onSuccess(Update response) {

                        tipDialog = new SuccessDialogUtils(mActivity, R.style.loading_dialog, "上传成功", R.mipmap.ic_right, true);
                        tipDialog.show();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {

                                Intent intent = new Intent();
                                setResult(666, intent);

                                finish();
                                tipDialog.dismiss();
                            }
                        }, 1000);
                    }

                    @Override
                    public void onUpdating() {

                    }

                    @Override
                    public void onUpdateFailed() {
                        tipDialog = new SuccessDialogUtils(mActivity, R.style.loading_dialog, "上传失败", R.mipmap.ic_error, true);
                        tipDialog.show();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                tipDialog.dismiss();
                            }
                        }, 1000);
                    }


                });
    }
    //endregion

    //region 返回定位点
    public void btn_restarlocation(){
        dingweiyuandian.setImageResource(R.mipmap.dingweizhong);
        LatLng latLng=new LatLng(lastPoints.latitude, lastPoints.longitude);
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(latLng).zoom(18.0f);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
    }
    //endregion

    //region 打卡
    public void Clockin(){
        if(lastPoints != null)
        {
            for(LatLng item : LatLng_List)
            {
                if(CroodUtils.getDistance(item,lastPoints)<1000)
                {

                    PointBean.DATA point = point_List.get(LatLng_List.indexOf(item));
                    String url = URLUtils.URLNoToken("manageAPI/bizClickin/add");

                    Map<String, String> map = new HashMap<String, String>();
                    map.put("patrolId", pId);//
                    map.put("pointId", String.valueOf(point.id));//
                    map.put("lonLat", item.longitude+","+item.latitude);

                    Gson gson = new Gson();
                    final String s = gson.toJson(map);

                    OkHttpUtils
                            .postString()
                            .url(url)
                            .addHeader("Authorization", AccountManager.getToken())
                            .mediaType(MediaType.parse("application/json; charset=utf-8"))
                            .content(s)
                            .build()
                            .execute(new UpdateCallback<Update>(mContext) {

                                @Override
                                public void onSuccess(Update response) {

                                    ToastUtils.show(mContext, point.pileNum + "点位打卡成功");
                                }

                                @Override
                                public void onUpdating() {

                                }

                                @Override
                                public void onUpdateFailed() {

                                }
                            });

                }
            }
        }
    }
    //endregion

    @Override
    protected void onTvLeftClicked() {
        super.onTvLeftClicked();
        initDialogInfo();
    }

    @Override
    protected void onTvRightClicked() {
        super.onTvRightClicked();
//        openActivity(PatrolCreateActivity.class,false);
        Bundle bundle = new Bundle();
        bundle.putString("pId", pId);
        openActivity(SignRecordsActivity.class, bundle, false);
    }
}